<template>
  <div class="tags-view-container">
    <el-scrollbar ref="scrollbarRef" class="tags-view-wrapper" @wheel.prevent="handleScroll">
      <div class="tags-view-scroll">
        <router-link
          v-for="tag in visitedTags"
          :key="tag.path"
          :to="tag.path"
          class="tags-view-item"
          :class="isActive(tag) ? 'active' : ''"
          @click.middle="closeSelectedTag(tag)"
          @contextmenu.prevent="openMenu(tag, $event)"
        >
          <el-icon v-if="tag.meta && tag.meta.icon" class="tag-icon">
            <component :is="tag.meta.icon" />
          </el-icon>
          <span>{{ t(tag.meta.title) }}</span>
          <el-icon class="close-icon" @click.prevent.stop="closeSelectedTag(tag)">
            <Close />
          </el-icon>
        </router-link>
      </div>
    </el-scrollbar>
    
    <!-- 右键菜单 -->
    <ul v-show="visible" :style="{ left: left + 'px', top: top + 'px' }" class="contextmenu">
      <li @click="refreshSelectedTag(selectedTag)">{{ t('tags.refresh') }}</li>
      <li v-if="!isFirstTag()" @click="closeSelectedTag(selectedTag)">{{ t('tags.close') }}</li>
      <li @click="closeOthersTags">{{ t('tags.closeOthers') }}</li>
      <li @click="closeAllTags">{{ t('tags.closeAll') }}</li>
    </ul>
  </div>
</template>

<script setup>
import { ref, computed, watch, nextTick, onMounted, onBeforeUnmount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import { Close } from '@element-plus/icons-vue'
import { useAppStore } from '@/stores/app'

const appStore = useAppStore()
const route = useRoute()
const router = useRouter()
const { t } = useI18n()

// 滚动条引用
const scrollbarRef = ref(null)

// 右键菜单状态
const visible = ref(false)
const top = ref(0)
const left = ref(0)
const selectedTag = ref({})

// 已访问的标签
const visitedTags = computed(() => appStore.visitedTags)

// 初始化
const initTags = () => {
  addTag(route)
  moveToCurrentTag()
}

// 添加标签
const addTag = (tag) => {
  if (tag.name && tag.meta && !tag.meta.hidden && tag.meta.title) {
    appStore.addVisitedTag(tag)
  }
}

// 判断是否为激活标签
const isActive = (tag) => {
  return tag.path === route.path
}

// 判断是否为第一个标签
const isFirstTag = () => {
  return visitedTags.value.length > 0 && visitedTags.value[0].path === selectedTag.value.path
}

// 关闭选中的标签
const closeSelectedTag = (tag) => {
  appStore.removeVisitedTag(tag)
  if (isActive(tag)) {
    toLastTag()
  }
}

// 刷新选中的标签
const refreshSelectedTag = (tag) => {
  // 保存当前路径和参数
  const { path, query, params } = tag
  
  router.replace({
    path: '/redirect' + path,
    query: query,
    params: params
  })
}

// 关闭其他标签
const closeOthersTags = () => {
  appStore.removeOtherVisitedTags(selectedTag.value)
  router.push(selectedTag.value.path)
}

// 关闭所有标签
const closeAllTags = () => {
  appStore.removeAllVisitedTags()
  router.push('/')
}

// 打开右键菜单
const openMenu = (tag, e) => {
  const menuMinWidth = 105
  
  // 获取点击的标签元素
  const tagEl = e.target.closest('.tags-view-item')
  if (!tagEl) return
  
  // 获取元素位置
  const rect = tagEl.getBoundingClientRect()
  const offsetTop = rect.top
  const offsetLeft = rect.left
  
  // 设置上下文菜单位置
  left.value = offsetLeft
  top.value = offsetTop + rect.height + 5 // 位于标签下方
  
  visible.value = true
  selectedTag.value = tag
}

// 关闭右键菜单
const closeMenu = () => {
  visible.value = false
}

// 跳转到最后一个标签
const toLastTag = () => {
  const latestView = visitedTags.value.slice(-1)[0]
  if (latestView) {
    router.push(latestView.path)
  } else {
    router.push('/')
  }
}

// 移动到当前标签
const moveToCurrentTag = async () => {
  await nextTick()
  if (!scrollbarRef.value) return
  
  for (const tag of visitedTags.value) {
    if (tag.path === route.path) {
      // 计算滚动位置
      const tagEl = document.querySelector(`.tags-view-item.active`)
      if (!tagEl) return
      
      try {
        const container = scrollbarRef.value.$el
        const containerWidth = container.offsetWidth
        const tagWidth = tagEl.offsetWidth
        const tagOffsetLeft = tagEl.offsetLeft
        
        let newLeft = tagOffsetLeft - (containerWidth - tagWidth) / 2
        
        scrollbarRef.value.setScrollLeft(Math.max(newLeft, 0))
      } catch (error) {
        console.error('移动到当前标签出错:', error)
      }
      break
    }
  }
}

// 处理滚动
const handleScroll = (e) => {
  const delta = e.wheelDelta || -e.deltaY
  if (scrollbarRef.value) {
    try {
      // 获取当前滚动位置
      const currentScrollLeft = scrollbarRef.value.wrapRef?.scrollLeft;
      
      // 只有当wrapRef和scrollLeft存在时才设置滚动
      if (scrollbarRef.value.wrapRef && currentScrollLeft !== undefined) {
        scrollbarRef.value.setScrollLeft(currentScrollLeft - delta / 4)
      } else if (scrollbarRef.value.wrap$ && scrollbarRef.value.wrap$.scrollLeft !== undefined) {
        // 兼容旧版本Element Plus
        scrollbarRef.value.setScrollLeft(scrollbarRef.value.wrap$.scrollLeft - delta / 4)
      }
    } catch (error) {
      console.error('滚动处理出错:', error)
    }
  }
}

// 监听路由变化
watch(
  () => route.path,
  () => {
    addTag(route)
    moveToCurrentTag()
  }
)

// 点击页面其他地方关闭右键菜单
const closeMenuOnClick = () => {
  closeMenu()
}

onMounted(() => {
  initTags()
  document.addEventListener('click', closeMenuOnClick)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', closeMenuOnClick)
})
</script>

<style lang="scss" scoped>
.tags-view-container {
  position: relative;
  height: 38px;
  width: calc(100% - 32px);
  margin: 10px 16px;
  background: #fff;
  border-radius: var(--el-border-radius-base);
  border-bottom: 1px solid #d8dce5;
  box-shadow: var(--el-box-shadow-light);
  
  .tags-view-wrapper {
    width: 100%;
    height: 100%;
    overflow: hidden;
    
    .tags-view-scroll {
      white-space: nowrap;
      padding: 0 10px;
      position: relative;
      height: 37px;
      
      .tags-view-item {
        display: inline-block;
        position: relative;
        height: 28px;
        line-height: 28px;
        border: 1px solid #d8dce5;
        background: #fff;
        color: #495060;
        padding: 0 8px;
        font-size: 13px;
        margin-right: 5px;
        margin-top: 5px;
        text-decoration: none;
        border-radius: 4px;
        transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
        
        .tag-icon {
          margin-right: 4px;
          vertical-align: -2px;
        }
        
        .close-icon {
          width: 16px;
          height: 16px;
          margin-left: 6px;
          border-radius: 50%;
          transition: all 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
          transform: translateY(1px);
          cursor: pointer;
          &:hover {
            background-color: #b4bccc;
            color: #fff;
          }
        }
        
        &:first-of-type {
          margin-left: 5px;
        }
        
        &:hover {
          color: #409EFF;
          border-color: #c6e2ff;
          background-color: #ecf5ff;
        }
        
        &.active {
          color: #fff;
          background-color: #409EFF;
          border-color: #409EFF;
          
          &::before {
            content: "";
            background: #fff;
            display: inline-block;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            position: relative;
            margin-right: 6px;
          }
          
          .close-icon {
            &:hover {
              background-color: rgba(255, 255, 255, 0.3);
              color: #fff;
            }
          }
        }
      }
    }
  }
  
  .contextmenu {
    position: fixed;
    background: #fff;
    z-index: 3000;
    list-style-type: none;
    padding: 5px 0;
    border-radius: 4px;
    font-size: 13px;
    font-weight: 400;
    color: #333;
    box-shadow: 2px 2px 3px 0 rgba(0, 0, 0, 0.3);
    margin: 0;
    
    li {
      margin: 0;
      padding: 8px 16px;
      cursor: pointer;
      &:hover {
        background: #eee;
      }
    }
  }
}
</style>
